package org.erp.store.infrastructure.listener;

import lombok.extern.log4j.Log4j2;
import org.erp.common.enums.DeviceInventoryEvent;
import org.erp.store.domain.entity.DeviceInventory;
import org.erp.store.domain.entity.InventoryLog;
import org.erp.store.infrastructure.enums.DeviceInventoryState;
import org.erp.store.infrastructure.event.InventoryLogEvent;
import org.erp.store.service.InventoryLogService;
import org.erp.store.infrastructure.convert.InventoryLogConvert;
import org.erp.store.infrastructure.util.IdempotencyKeyUtil;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Log4j2
@Component
public class InventoryLogEventListener {

    @Resource
    private InventoryLogService inventoryLogService;
    @Resource
    private InventoryLogConvert inventoryLogConvert;

    @Async("inventoryLogExecutor")
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void handle(InventoryLogEvent event) {
        List<DeviceInventory> list = event.getDeviceInventoryList();
        DeviceInventoryEvent targetEvent=event.getTargetEvent();
        Map<String, Integer> originalStateMap=event.getOriginalStateMap();
        if (list == null || list.isEmpty()) {
            log.info("无库存修改记录，不处理");
            return;
        }
        try {
            // 1. 记录库存日志
            List<InventoryLog> inventoryLogList = new ArrayList<>();
            Date now = new Date();
            for (DeviceInventory inv : list) {
                InventoryLog inventoryLog = new InventoryLog();
                inventoryLog.setProductCode(inv.getProductCode());
                inventoryLog.setEventType(targetEvent.getMessage());
                inventoryLog.setOperateId(inv.getOperateId());
                inventoryLog.setIdempotencyKey(IdempotencyKeyUtil.buildStatusUpdateKey(inv.getProductCode(), inv.getOperateId()));
                inventoryLog.setOperateName(inv.getOperateName());
                inventoryLog.setStageBefore(DeviceInventoryState.getMessageByCode(originalStateMap.get(inv.getProductCode())));
                inventoryLog.setStageAfter(DeviceInventoryState.getMessageByCode(inv.getStatus()));
                inventoryLog.setEventDate(now);
                inventoryLogList.add(inventoryLog);
            }
            if (!inventoryLogList.isEmpty()) {
                inventoryLogService.saveBatch(inventoryLogList);
                log.info("日志监听写入完成，保存数量={}", inventoryLogList.size());
            } else {
                log.info("日志监听写入完成，无需保存");
            }
        } catch (Exception e) {
            log.error("库存日志事件处理失败，错误：{}", e.getMessage(), e);
            throw new RuntimeException("库存日志事件处理失败", e);
        }
    }


}
